const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');
var p = 0,
  t = 0;
var checkValue = [];
var checkCountry = [];
var pageno_ = 1;

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navTop: app.globalData.navHeight,
    back: true,
    navBox: true,
    searchTop: 1,
    searchInput: '请搜索麦德龙商品',
    searchValue: '',
    showView: false,
    arrange: "list",
    isopen: true,
    navCont: 0, //购物车商品数量
    scrollHeight: app.globalData.windowHeight - app.globalData.navHeight - 40,
    itemdetail: [],
    select: 0, //选中
    flag: 2,
    sure: 0,
    navcataid: '',
    nomore: false,
    scrollTop: 0,
    goTop: true,
    goPage: true,
    bnimMin: {},
    bnimList: {},
    bnimLayer: {},
    bnimationWidth: app.globalData.windowWidth * 0.85,
    buttons: [{
      id: true,
      name: '自提'
    }, {
      id: false,
      name: '非自提'
    }],
    brandsDialog: false,
    originsDialog: false,
    cateDialog: false,
    showSkeleton: true,
    pageno_: 1,
    pageCount_: 0,
    totalpage: 0,
    listLock: 1, //列表翻页锁
    sortID: 0
  },

  // 切换列表显示方式
  onChangeShowState: function () {
    let that = this;
    if (that.data.isopen) {
      that.setData({
        arrange: "repeat"
      })
    } else {
      that.setData({
        arrange: "list"
      })
    }
    that.data.isopen = !that.data.isopen
    that.setData({
      showView: !that.data.showView
    });

  },

  //点击弹出
  openplus: function () {
    this.bnimationpopp();
    this.setData({
      buttons: this.data.buttons
    })
  },

  // 配送方式
  radioButtonTap: function (e) {
    let id = e.currentTarget.dataset.id
    for (let i = 0; i < this.data.buttons.length; i++) {
      if (this.data.buttons[i].id == id) {
        //当前点击的位置为true即选中
        this.data.buttons[i].checked = true;
      } else {
        //其他的位置为false
        this.data.buttons[i].checked = false;
      }
    }

    this.setData({
      buttons: this.data.buttons
    })

  },

  digitminPrice: function (e) {
    var value = e.detail.value;
    this.setData({
      digitmin: e.detail.value.replace(/^\s+|\s+$/g, '')
    })

  },

  digitmaxPrice: function (e) {
    var value = e.detail.value;
    this.setData({
      digitmax: e.detail.value.replace(/^\s+|\s+$/g, '')
    })

  },

  // 品牌
  // checkboxList: function (e) {
  //   var that = this;
  //   var index = e.currentTarget.dataset.index;
  //   var brands = this.data.brands;
  //   brands[index].checked = !brands[index].checked;
  //   this.setData({
  //     brands: brands
  //   });

  //   if (brands[index].checked == true) {
  //     checkValue.push(brands[index])
  //   }

  //   if (brands[index].checked == false) {
  //     checkValue.splice(brands[index], 1)
  //   }

  // },

  checkboxChange: function (e) {
    var checkValue = e.detail.value;
    this.setData({
      checkValue: checkValue,
      brandlist: checkValue.join('、'),
      brandlength: checkValue.length
    });

  },

  // 产地
  // checkboxArea: function (e) {
  //   var that = this;
  //   var index = e.currentTarget.dataset.index;
  //   var origins = this.data.origins;
  //   origins[index].checked = !origins[index].checked;
  //   this.setData({
  //     origins: origins
  //   });

  //   if (origins[index].checked == true) {
  //     checkCountry.push(origins[index])
  //   }

  //   if (origins[index].checked == false) {
  //     checkCountry.splice(origins[index], 1)
  //   }
  // },

  // checkboxorigins: function (e) {
  //   var checkValue = e.detail.value;
  //   this.setData({
  //     checkCountry: checkValue,
  //     countrylist: checkValue.join('、'),
  //     countrylength: checkValue.length
  //   });

  // },

  // radioChange: function (e) {
  //   var that = this;
  //   var radioValue = e.detail.value;
  //   this.setData({
  //     kindlist: radioValue
  //   })
  //   if (radioValue != "" || radioValue != null || radioValue != undefined) {
  //     that.setData({
  //       cateDialog: false
  //     })
  //   }

  // },

  // 分类
  // sortCate: function () {
  //   var that = this;
  //   that.setData({
  //     cateDialog: true
  //   })

  // },

  // 品牌查更多
  // brandsLook: function () {
  //   var that = this;
  //   that.setData({
  //     brandsDialog: true
  //   })

  // },

  // 产地查更多
  // originsLook: function () {
  //   var that = this;
  //   that.setData({
  //     originsDialog: true
  //   })

  // },

  // formSubmit: function (e) {
  //   var that = this;
  //   that.closemin()

  // },

  // formReset: function (e) {
  //   var that = this;
  //   var buttons = this.data.buttons;
  //   var origins = this.data.origins;
  //   var kinds = this.data.kinds;

  //   for (var i = 0; i < buttons.length; i++) {
  //     buttons[i].checked = false;
  //   }

  //   for (var i = 0; i < kinds.length; i++) {
  //     kinds[i].checked = false;
  //   }

  //   this.setData({
  //     buttons: this.data.buttons,
  //     kinds: kinds,
  //     kindlist: ''
  //   })

  //   that.resetBrand()
  //   that.resetOrigin()
  // },

  //点击收起
  closemin: function () {
    this.tackback();
  },

  //弹出动画
  bnimationpopp: function () {
    var bnimationMin = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var bnimationList = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var bnimationLayer = wx.createAnimation({
      duration: 10,
      timingFunction: 'ease-out'
    })

    bnimationMin.translate(-this.data.bnimationWidth, 0).opacity(1).step();
    bnimationList.translate(-this.data.bnimationWidth, 0).opacity(1).step();
    bnimationLayer.width(wx.getSystemInfoSync().windowWidth).opacity(1).step();
    this.setData({
      bnimMin: bnimationMin.export(),
      bnimList: bnimationList.export(),
      bnimLayer: bnimationLayer.export()
    })
  },

  //收回动画
  tackback: function () {
    var bnimationMin = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var bnimationList = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out'
    })
    var bnimationLayer = wx.createAnimation({
      duration: 10,
      timingFunction: 'ease-out'
    })
    bnimationMin.translate(0, 0).opacity(0).step();
    bnimationList.translate(0, 0).opacity(0).step();
    bnimationLayer.width(0).opacity(0).step();
    this.setData({
      bnimMin: bnimationMin.export(),
      bnimList: bnimationList.export(),
      bnimLayer: bnimationLayer.export(),
      brandsDialog: false,
      originsDialog: false,
      cateDialog: false
    })
  },

  // 清除品牌
  // resetBrand: function () {
  //   var that = this;
  //   var brands = this.data.brands;
  //   for (var i = 0; i < brands.length; i++) {
  //     brands[i].checked = false
  //   }
  //   that.setData({
  //     brands: brands,
  //     brandlength: '',
  //     brandlist: ''
  //   })
  // },

  // 清除产地
  // resetOrigin: function () {
  //   var that = this;
  //   var origins = this.data.origins;
  //   for (var i = 0; i < origins.length; i++) {
  //     origins[i].checked = false
  //   }
  //   that.setData({
  //     origins: origins,
  //     countrylength: '',
  //     countrylist: ''
  //   })
  // },

  //关闭二级弹层
  closeSec: function () {
    var that = this;
    that.setData({
      brandsDialog: false,
      originsDialog: false,
      cateDialog: false
    })
  },

  //关键词搜索
  searchItem: function () {
    var that = this;
    var searchValue = that.data.searchValue;
    var navcataid = that.data.navcataid;
    var sortID = that.data.sortID;
    var pageno_ = that.data.pageno_
    wx.showLoading({
      title: '加载中...',
    })
    console.log(that.data.navcataid)
    wx.request({
      url: util.api + api.SearchProduct,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          combo: 0,
          cid: navcataid,
          keyword: searchValue,
          sort: sortID,
          pageNo: pageno_,
          brandIds: "",
          origin: "",
          IsZiti: 0,
          minprice: 0,
          maxprice: 0,
          first: true
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.RESULT)
        var lily = res.data.RESULT['<ProductList>k__BackingField']['<List>k__BackingField']
        if (navcataid != "" || navcataid != null || navcataid != undefined){
        // 响应无数据 则提示无数据
        if (pageno_ == 1 && lily.length == 0) {
          that.setData({
            itemdetail: true
          })
        }
        if (lily.length) {
          that.data.totalcount = res.data.RESULT['<ProductList>k__BackingField']['<TotalItemCount>k__BackingField']
          that.data.pageCount_ = res.data.RESULT['<ProductList>k__BackingField']['<PageCount>k__BackingField']

          var deviceListTemp = [];

          if (pageno_ > 1) {
            deviceListTemp = that.data.itemdetail.concat(lily);
            that.setData({
              searchLoading: true, //"正在载入更多"显示
              pageno_: res.data.RESULT['<ProductList>k__BackingField']['<PageNumber>k__BackingField'],
              pageCount_: res.data.RESULT['<ProductList>k__BackingField']['<PageCount>k__BackingField']
            });
            console.log(res.data.RESULT['<ProductList>k__BackingField']['<PageCount>k__BackingField'])
          } else {
            deviceListTemp = lily;
          }
          
          
          if (that.data.select == 0) {
            that.setData({
              itemdetail: deviceListTemp
            })
          }

          if (that.data.select == 1) {

            if (that.data.flag == 0) {
              that.setData({
                itemdetail: deviceListTemp
              })
            }

            if (that.data.flag == 1) {
              that.setData({
                itemdetail: deviceListTemp
              })
            }

          }

          if (that.data.select == 2) {
            that.setData({
              itemdetail: deviceListTemp
            })
          }

        //   //判断综合排序

        //   var t;
        // if (that.data.select == 0) {
        //     for (var i = 0; i < deviceListTemp.length; i++) {
        //       var rand = parseInt(Math.random() * deviceListTemp.length);
        //       t = deviceListTemp[rand];
        //       deviceListTemp[rand] = deviceListTemp[i];
        //       deviceListTemp[i] = t;
        //     }
        //     // sortID = 0;
            // that.setData({
            //   itemdetail: deviceListTemp
            // })

        //}

        //   //判断价格排序
        //   if (that.data.select == 1) {
        //     if (that.data.flag == 0) {
        //       //价格升序
        //       deviceListTemp.sort(function (a, b) {
        //         return parseInt(a["['<Price>k__BackingField']"]) - parseInt(b["['<Price>k__BackingField']"])
        //       })
        //       // sortID = 3;
        //       that.setData({
        //         itemdetail: deviceListTemp
        //       })
        //     }
        //     if (that.data.flag == 1) {
        //       //价格降序
        //       deviceListTemp.sort(function (a, b) {
        //         return parseInt(b["['<Price>k__BackingField']"]) - parseInt(a["['<Price>k__BackingField']"])
        //       })
        //       // sortID = 4;
        //       that.setData({
        //         itemdetail: deviceListTemp
        //       })
        //     }

        //   }

        //   //判断销量排序
        //   if (that.data.select == 2) {
        //     if (that.data.sure == 0) {
        //       //销量升序
        //       deviceListTemp.sort(function (a, b) {
        //         return parseInt(a["['<StockNum>k__BackingField']"]) - parseInt(b["['<StockNum>k__BackingField']"])
        //       })
        //       // sortID = 6;
        //       that.setData({
        //         itemdetail: deviceListTemp
        //       })
        //     } else {
        //       //销量降序
        //       deviceListTemp.sort(function (a, b) {
        //         return parseInt(b["['<StockNum>k__BackingField']"]) - parseInt(a["['<StockNum>k__BackingField']"])
        //       })
        //       // sortID = 6;
        //       that.setData({
        //         itemdetail: deviceListTemp
        //       })
        //     }
        //   }

        //   // that.setData({
        //   //   itemdetail: deviceListTemp, //获取数据数组
        //   //   noData: false //“没有数据”隐藏
        //   // });

        }



        console.log(that.data.itemdetail)
      }  
        /*
                  // 品牌产地
                  var brands = [];
                  var origins = [];
                  var brandObj = {};
                  var originsObj = {};
                  for (var i = 0; i < lily.length; i++) {
                    for (var j = 0; j < lily[i].brands.length; j++) {
                      brands.push(lily[i].brands[j])
                    }
                    for (var k = 0; k < lily[i].origins.length; k++) {
                      origins.push(lily[i].origins[k])
                    }
                  }

                  brands = brands.reduce(function(item, next) {
                    brandObj[next.value] ? '' : brandObj[next.value] = true && item.push(next);
                    return item;
                  }, []);

                  origins = origins.reduce(function(item, next) {
                    originsObj[next.value] ? '' : originsObj[next.value] = true && item.push(next);
                    return item;
                  }, []);

                  that.setData({
                    brands: brands,
                    origins: origins
                  })
        */
        /*
                  //判断综合排序
                  
                  var t;
                  if (that.data.select == 0) {
                    for (var i = 0; i < lily.length; i++) {
                      var rand = parseInt(Math.random() * lily.length);
                      t = lily[rand];
                      lily[rand] = lily[i];
                      lily[i] = t;
                    }
                    // sortID = 0;
                    that.setData({
                      itemdetail: lily
                    })

                  }

                  //判断价格排序
                  if (that.data.select == 1) {
                    if (that.data.flag == 0) {
                      //价格升序
                      lily.sort(function(a, b) {
                        return parseInt(a["['<Price>k__BackingField']"]) - parseInt(b["['<Price>k__BackingField']"])
                      })
                      // sortID = 3;
                      that.setData({
                        itemdetail: lily
                      })
                    }
                    if (that.data.flag == 1) {
                      //价格降序
                      lily.sort(function(a, b) {
                        return parseInt(b["['<Price>k__BackingField']"]) - parseInt(a["['<Price>k__BackingField']"])
                      })
                      // sortID = 4;
                      that.setData({
                        itemdetail: lily
                      })
                    }
                    
                  }

                  //判断销量排序
                  if (that.data.select == 2) {
                    if (that.data.sure == 0) {
                      //销量升序
                      lily.sort(function(a, b) {
                        return parseInt(a["['<StockNum>k__BackingField']"]) - parseInt(b["['<StockNum>k__BackingField']"])
                      })
                      // sortID = 6;
                      that.setData({
                        itemdetail: lily
                      })
                    } else {
                      //销量降序
                      lily.sort(function(a, b) {
                        return parseInt(b["['<StockNum>k__BackingField']"]) - parseInt(a["['<StockNum>k__BackingField']"])
                      })
                      // sortID = 6;
                      that.setData({
                        itemdetail: lily
                      })
                    }
                  }
        */


        that.setData({
          showSkeleton: false
        })
        wx.hideLoading()
      },
      fail: function (res) {
        that.setData({
          showSkeleton: false
        })
        wx.hideLoading()
      },
      complete: function (res) {
        that.setData({
          showSkeleton: false
        })
        wx.hideLoading()
      }
    })
  },


  //点击综合排序
  comprehensive: function () {
    var that = this;
    that.setData({
      select: 0,
      flag: 2,
      sortID: 0
    })

    that.searchItem();

  },

  //价格
  priceSort: function (e) {
    var that = this;
    var sel = e.currentTarget.dataset.sel;
    if (sel == 1) {
      if (that.data.flag = !that.data.flag) {
        that.setData({
          flag: 1,
          sortID: 3
        })

      } else {
        that.setData({
          flag: 0,
          sortID: 4
        })

      }
      that.setData({
        select: 1
      })
    }

    that.searchItem();
  },

  //销量
  salesVolume: function (e) {
    var that = this;
    var sel = e.currentTarget.dataset.sel;
    if (sel == 2) {
      if (that.data.sure = !that.data.sure) {
        that.setData({
          sure: 1,
          sortID: 6
        })

      } else {
        that.setData({
          sure: 0,
          sortID: 6
        })

      }
      that.setData({
        select: 2,
        flag: 2
      })
    }

    that.searchItem();
  },

  touchStart: function (e) {
    var that = this;
    that.setData({
      goPage: false,
      goTop: true
    });
  },

  touchEnd: function (e) {
    var that = this;
    setTimeout(function () {
      that.setData({
        goTop: false,
        goPage: true
      });
    }, 1000)
  },

  scroll: function (e) {
    var that = this;
    var listIndex = (e.detail.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.4)
    if (e.detail.scrollTop > app.globalData.navHeight + 40) {
      that.setData({
        goPage: false
      });
      this.setData({
        listIndex: listIndex
      })
      console.log("123123")
    } else {
      this.setData({
        goTop: true
      });
      console.log("sdfsdf")
    }

  },

  //返回顶部
  goScrolltop: function (e) {
    var that = this;
    var top = that.data.scrollTop;
    if (top == 1) {
      top = 0;
    } else {
      top = 1;
    }

    that.setData({
      scrollTop: top
    })

  },

  bindscrolltolower: function (e) {
    var that = this;
    var pageno_ = that.data.pageno_;
    pageno_++
    if (pageno_ < that.data.pageCount_) {
      that.setData({
        pageno_: pageno_ + 1, //每次触发触底事件，把pageno_+1
      });
      console.log(pageno_)

      that.searchItem(pageno_);
    } else if (pageno_ == that.data.pageCount_) {
      that.setData({
        searchLoadingComplete: true, //“已加载全部”显示
        searchLoading: false //"正在载入更多"隐藏
      });
    }
    //var pageno = this.data.pageno;
    // pageno += 1;
    // this.searchItem();
    //this.data.pageno = this.data.pageno + 1;
    this.setData({
      nomore: true
      //pageno: pageno
    })
  },

  // 加入购物车
  addCart: function (e) {
    var that = this;
    var itemdetail = that.data.itemdetail;
    var id = e.currentTarget.dataset.id;
    that.cartNumber();
    $Toast({
      content: "加入购物车成功!",
      icon: 'success',
      duration: 1
    });

    for (var i = 0; i < itemdetail.length; i++) {
      if (itemdetail[i].id == id) {
        // 给itemdetail数组的当前项添加count元素，值为1，用于记录添加到购物车的数量
        itemdetail[i].count = 1;
        itemdetail[i].checked = true;
        var arr = wx.getStorageSync('shopCart') || [];
        if (arr.length > 0) {
          for (var j in arr) {
            if (arr[j].id == id) {
              arr[j].count = arr[j].count + 1;
              try {
                wx.setStorageSync('shopCart', arr)
              } catch (e) {
                console.log(e)
              }
              return;
            }
          }
          arr.push(itemdetail[i]);
        } else {
          arr.push(itemdetail[i]);
        }

        try {
          wx.setStorageSync('shopCart', arr)
          return;
        } catch (e) {
          console.log(e)
        }
      }
    }

  },

  //页面加载时购物车数量
  countCart: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          var counts = 0;
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts = parseInt(counts) + parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {}
    })
  },

  //加入购物车实时数量
  cartNumber: function () {
    var that = this;
    var arr = wx.getStorageSync('shopCart');
    var counts = 1;
    //遍历购物车缓存对其进行求和
    for (var i = 0; i < arr.length; i++) {
      counts = parseInt(counts) + parseInt(arr[i].count);
    }
    let navCont = this.data.navCont;
    //购物车商品数量
    that.setData({
      navCont: counts
    })
  },


  collectionTap: function (e) {
    var that = this;
    var itemdetail = that.data.itemdetail;
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;

    $Toast({
      content: "收藏成功!",
      icon: 'success',
      duration: 1
    });
    for (var i = 0; i < itemdetail.length; i++) {
      if (itemdetail[i].id == id) {
        itemdetail[i].count = 1;
        itemdetail[i].checked = true;
        var arr = wx.getStorageSync('shopCollect') || [];
        if (arr.length > 0) {
          for (var j in arr) {
            if (arr[j].id == id) {
              $Toast({
                content: '此商品已收藏!',
                icon: 'prompt_fill',
                duration: 1
              });

              try {
                wx.setStorageSync('shopCollect', arr)
              } catch (e) {
                console.log(e)
              }
              return;
            }
          }
          arr.push(itemdetail[i]);
        } else {
          arr.push(itemdetail[i]);
        }
        try {
          wx.setStorageSync('shopCollect', arr)
          return;
        } catch (e) {
          console.log(e)
        }
      }
    }
  },

  gotoDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var navcataid = that.data.navcataid;
    // wx.navigateTo({
    //   url: '../productdetail/productdetail?id=' + id + '&navcataid=' + navcataid
    // })
    util.navigateTo('../productdetail/productdetail?id=' + id + '&navcataid=' + navcataid)
  },

  toShop: function () {
    util.navigateTo('../cart/cart')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // pageno = 1;
    this.searchItem();
    try {
      var search = options.search;
      var navcataid = options.navcataid;
      that.setData({
        searchValue: search,
        navcataid: navcataid
      })
      
    } catch (e) {
      console.log(e)
    }
    that.setData({
      kinds: [{
        "key": "0",
        "value": "全部分类"
      }]
    })

    //获取屏幕尺寸
    const screenWidth = wx.getSystemInfoSync().windowWidth;
    const screenHeight = wx.getSystemInfoSync().windowHeight;
    this.setData({
      listIndex: screenHeight / (screenWidth * 0.4),
      screenWidth: screenWidth,
      screenHeight: screenHeight
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.countCart()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }


})